$(function(){
    $('.c').corner();
});

var counter = 0;
var load_info = function(){ return true };
var filter_options = new Object;

/* begin: requestBuilder builds string for GET query. This string contains filter options and additional columns */
var	requestBuilder = function (oState, oSelf) {
    if ('' == window.location_search) {
        s = '?';
        for (var i in filter_options) {
            if (filter_options[i]) {
                if (!(i.indexOf('col_')==0)) {
                    s += 'filter_by_' + i + '=' + filter_options[i].replace(' ', '+').replace('&', '%26') + '&';
                } else {
                    s+=i.replace('&', '%26').replace(' ', '+')+'&';
                };
            };
        };
        return s;
    } else {
        ls = window.location_search;
        window.location_search = '';
        return ls;
    };
}
/* end: requestBuilder */

var ResultsDataTableDeferred;
/* This var is needed for determine if DataTable should start InitialLoad */
var location_search = location.search;
/* Freebase-suggest options */
var bv_options = {
    soft: true,
    ac_param: {
        type: BIOVENTURIST_DIR + "bv_medical_condition",
        start: 0,
        limit: 30
    }
};


var update_filters_div = function() {
    var filter_s = "";
    for (var k in window.filter_options) {
        if (k.substr(0,4) == 'col_') {
            continue;
        };
        var label = window.ResultsDataTableDeferred.getColumn(k).label;
        if (window.filter_options[k]) {
            filter_s += label + ': ' + window.filter_options[k] + ', ';
        };
    };
    if ("" != filter_s) {
        jQuery("#filters").html('for <strong>' + filter_s.substr(0,filter_s.length-2) + '</strong>');
    } else {
        jQuery("#filters").text('');
    };
};


function add_suggest(){
    $('input.filter_query').each(function(){
        var s = $(this).siblings('select.filter_type');
        var v = s.val()
        bv_options['ac_param']['type']=type_for_freebase_suggest(v);
        $(this).freebaseSuggest(bv_options);
    });
};


YAHOO.util.Event.addListener(window, "load", function() {
    /* Add Freebase Suggest to filter text-field */
    jQuery("select.filter_type").live("change", function(){
            bv_options['ac_param']['type'] = type_for_freebase_suggest($(this).val());
            $(this).siblings('input.filter_query').freebaseSuggest(bv_options);
        });

    /* Switch a text input to freebase-suggest field at first time */
    bv_options['ac_param']['type']=type_for_freebase_suggest($("select.filter_type").val());
    $("input.filter_query").freebaseSuggest(bv_options);

    /* begin: SearchPage object -- helper functions */
    with(SearchPage=new Function){

        /* Update string which shows "Showing 1-5 of 10 ..." */
        prototype.update_results_count=function(records, totalRecords) {
            var start_index = 0;
            var end_index = totalRecords;
            if (records != null) {
                start_index = records[0] + 1;
                end_index = records[1] + 1;
            };
            jQuery('#records_index').text(start_index + '-' + end_index + ' of ');
        };
    };
    /* end: SearchPage object -- helper functions */
    var searchPage = new SearchPage();

    /* begin: Table object */
    with(Table=new Function){

        /* Reset table */
        prototype.reset=function(){

            var oState = ResultsDataTableDeferred.getState(), request, oCallback;
            var records = oState.pagination.records;
            var totalRecords = oState.pagination.totalRecords;
            request = ResultsDataTableDeferred.get("generateRequest")(oState, ResultsDataTableDeferred);            
            oCallback = {
                success : function(sRequest, oResponse, oPayload) {
                    var r = oResponse;
                    ResultsDataTableDeferred.onDataReturnInitializeTable(sRequest, oResponse, oPayload);
                    $("#img_loading").hide(); // Hide 'Loading' image (blue rolling circle)
                    // Update count of records in paragraph "Showing ... of ..."
                    var returned_results_count = oResponse.results.length;
                    var end_index = RECORDS_PER_PAGE;
                    if (returned_results_count<RECORDS_PER_PAGE) {
                        end_index = returned_results_count;
                    };
                    jQuery('#records_index').text('1-' + end_index + ' of ');
                    // Update filter options in paragraph "Showing ... of ..."
                    update_filters_div();
                },
                failure : function(sRequest, oResponse, oPayload) {
                    ResultsDataTableDeferred.onDataReturnInitializeTable(sRequest, oResponse, oPayload);
                    $("#img_loading").hide();
                },
                argument : oState,
                scope : ResultsDataTableDeferred
            }
            $("#img_loading").show();
            Results.sendRequest(request, oCallback);
        };

        /* Reload a table, e.g. when user adds or removes column */
        prototype.reload=function(){
            var oState = ResultsDataTableDeferred.getState();
            var records = oState.pagination.records;
            var totalRecords = oState.pagination.totalRecords;
            request = ResultsDataTableDeferred.get("generateRequest")(oState, ResultsDataTableDeferred);
            oCallback = {
                success : function(sRequest, oResponse, oPayload) {
                    ResultsDataTableDeferred.onDataReturnSetRows(sRequest, oResponse, oPayload);
                    $("#img_loading").hide();
                },
                failure : function(sRequest, oResponse, oPayload) {
                    ResultsDataTableDeferred.onDataReturnSetRows(sRequest, oResponse, oPayload);
                    $("#img_loading").hide();
                },
                argument : oState,
                scope : ResultsDataTableDeferred
            };
            $("#img_loading").show();
            Results.sendRequest(request, oCallback);
        };

        /* Construct HTML code of table for current results set  */
        prototype.view_as=function(v){
            switch(v) {
                case 'html':
                    var recordSet = ResultsDataTableDeferred.getRecordSet();
                    var columns = ResultsDataTableDeferred.getColumnSet().keys;
                    var records = recordSet.getRecords();
                    var l = recordSet.getLength();
                    // Construct HTML code for table
                    var timestamp = new Date().getTime();
                    var table_html = '<p>&nbsp;</p>\n<table class="company_search_results" id="company_search_results_' + timestamp + '">\n\n<thead>\n\n<tr>\n';
                    // Add column headers
                    for (var i=0;i<columns.length;i++) {
                        table_html += '<th>' + columns[i].label + '</th>';
                    }
                    table_html += '</tr>\n</thead>\n\n';
                    // Add rows
                    for (var i=0; i<l; i++) {
                        table_html += "<tr>\n"
                        for (var n=0;n<columns.length;n++) {
                            table_html  += '\t<td valign="top">'
                            d = recordSet.getRecord(i).getData(columns[n].key) || '&nbsp;'
                            if (typeof(d)=='object') {
                                var t = ''
                                for (var k=0;k<d.length;k+=1) {
                                    if (d[k]) {
                                        t = t + '<li>' + d[k] + '</li>';

                                    };
                                };
                                table_html += '<ul>' + t + '</ul>';
                            } else {
                                table_html += d;
                            };
                            table_html += '</td>\n';
                        };
                        table_html += '</tr>\n\n';
                    };
                    table_html += '</table>';
                    /* This is need for displaying table with Yahoo Interface in Analysis page */
                    table_html += '<div id="tc_company_search_results_' + timestamp + '">Don\'t remove this placeholder. It will be replaced.</div>\n<p>&nbsp;</p>\n';
                    return table_html;
                    break;
                default:
                    return false;
            }
        }
    }
    var table = new Table();
    /* end: Table object */


    /* begin: Filter object */
    with(Filter=new Function){

        prototype.q = new Object;

        /* Add filter field */
        prototype.add=function() {
            $('#filters_div').append(
                '<div class="filter_block">' +
                'and' +
                '&nbsp;<select class="filter_type" id="filter_type' + counter + '">' +
                $('select.first').html() +
                '</select>' +
                '&nbsp;<input type="text" size="10" class="filter_query" id="filter_query' + counter + '" />' +
                '&nbsp;<input type="button" class="filter_add" value="+" />' +
                '&nbsp;<input type="button" class="filter_rm" value="-" style="margin-right: 1.8em;" />' +
                '</div>'
            );
            add_suggest();
            counter += 1;
        };

        /* Remove filter field */
        prototype.rm=function(el) {
            $(el).parent().remove();
        };

        /* Getter of filter options hash */
        prototype.get_filter_options=function() {
            window.location_search = '';
            var t = new Object();
            // Save columns added by user
            for (var k in filter_options) {
                if ((k.indexOf('col_') != -1) || (k.indexOf('sort_by_') != -1)) {
                        t[k] = filter_options[k];
                };
            };
            $('select.filter_type').each(function(i){
                var v = $(this).siblings('input.filter_query').val() || "";
                t[$(this).val()] = v;
            });
            this.q = t;
            return this.q;
        };

        /* Apply filters to table */
        prototype.apply_to=function(table) {
            table.reset();
        };
    };
    var filter = new Filter();
    /* end: Filter object */


    /* Bind add filter action to buttons */
    $('input.filter_add').live('click', function(){
        filter.add();
    });

    /* Bind remove filter action to buttons */
    $('input.filter_rm').live('click', function(){
        filter.rm(this);
    });

    /* User clicks on "Filter" button */
    $('input.filter_run').click(function(){
        if (console) {console.log('clicked on search button')};
        filter_options = filter.get_filter_options();        
        filter.apply_to(table);
    });


    /* begin: SelectList object -- when user adds or removes columns from table */
    with(SelectList=new Function){

        prototype.with_table=function(table) {
            this.table = table;
            return this;
        };

        prototype.new_columns=function(new_cols) {
            if (!new_cols) { this.nc = [] };
            this.nc = new_cols;
            return this;
        };

        prototype.value=function() {
            var selected_key = "";
            var rm_list_css = jQuery("select#id_row_to_rm").css("display");
            if (rm_list_css=='none') {
                selected_key = jQuery("select#id_row_to_add").val()
            } else {
                selected_key = jQuery("select#id_row_to_rm").val()
            };
            return selected_key;
        };

        prototype.get_Column=function(key) {
            for (var i=0;i<this.nc.length;i++) {
                if (this.nc[i].key==key) {
                    return this.nc[i];
                };
            };
        };

        prototype.rebuild=function() {

            var columns_set = this.table.getColumnSet().keys;
            var columns_set_keys = [];
            var select_list_for_deletion = "";
            for(var i=0;i<columns_set.length;i++) {
                select_list_for_deletion += "<option value=\"" + columns_set[i].key + "\">" + columns_set[i].label + "</option>";
                columns_set_keys.push(columns_set[i].key);
            };
            $("select#id_row_to_rm").html(select_list_for_deletion);
            var select_list_for_add = "";
            for (var i = 0;i < this.nc.length;i++) {
                var b = false;
                for (var n=0;n<columns_set_keys.length;n++) {
                    if (this.nc[i].key==columns_set_keys[n]) {
                        b = true;
                    };
                };
                if (b) {
                    continue;
                } else {
                    select_list_for_add += "<option value=\"" + this.nc[i].key + "\">" + this.nc[i].label + "</option>";
                };
            };
            if (select_list_for_add == ""){
                select_list_for_add = "<option value=\"false\">No columns available</option>";
            };
            $("select#id_row_to_add").html(select_list_for_add);
        };
    };
    /* end: SelectList */

    /* begin: Paginator */
    var paginator = new YAHOO.widget.Paginator({rowsPerPage: RECORDS_PER_PAGE})

    /* Change numbers of current showing records in paragraph "Showing ... of ..." */
    paginator.subscribe('changeRequest', function(event) {
        var start_index = event.records[0] + 1;
        var end_index = event.records[1] + 1;
        jQuery('#records_index').text(start_index + '-' + end_index + ' of ');
        return true;
    });

    /* Change count of records in paragraph "Showing ... of ..." */
    paginator.subscribe('beforeTotalRecordsChange', function(event) {
        var count = event.newValue;
        jQuery('#total_records').text(count);
        return true;
    });
    /* end: Paginator */


    /* If we request page with params (e.g. whe user copy URL from 'Share') do initial load of data */
    var initialLoad = false;
    if (window.location_search != '') {
        initialLoad = true;
    };

    ResultsDataTableDeferred = new YAHOO.widget.ScrollingDataTable(
        "results",
        ResultsColumnDefs,
        Results,
        {
            paginator: paginator,
            generateRequest: requestBuilder,
            width: "889px",
            initialLoad: initialLoad,
            initialRequest: requestBuilder(),
            MSG_EMPTY: emptyMessage,
        }
    );


    var select_list = new SelectList().with_table(ResultsDataTableDeferred).new_columns(not_default_columns);

    jQuery('span.article_head').live('click', function(){
        $(this).css({'text-decoration': 'none', 'cursor': 'default', 'background': '#fff'});
        $(this).siblings('span.dots').hide();
        $(this).siblings('span.article_tail').show();
    });

    /* When user click on "Show more" link in unordered lists */
    jQuery('li.edge').live('click', function(){
        var result = '<ul style="margin: 2em;">'
        $(this).siblings('li').each(function(){
            result += '<li>' + $(this).html() + '</li>';
        });
        result += '</ul>';
        jQuery.facebox(result);
    });

    jQuery('a#id_rm_rows').click(function(event){
        select_list.rebuild();
        $('select#id_row_to_add').hide();
        $('input#id_button_row_add').hide();
        $('select#id_row_to_rm').toggle();
        $('input#id_button_row_rm').toggle();
    });


    jQuery('a#id_add_rows').click(function(event){
        select_list.rebuild();
        $('select#id_row_to_add').toggle();
        $('input#id_button_row_add').toggle();
        $('select#id_row_to_rm').hide();
        $('input#id_button_row_rm').hide();
    });


    /* When user cliecks Add Column button */
    jQuery('#id_button_row_add').click(function(event){
        var col_key = select_list.value();
        if (col_key=='false'){
            return;
        };
        filter_options['col_'+col_key] = true;
        Results.responseSchema.fields.push({key: col_key})
        column = select_list.get_Column(col_key)
        ResultsDataTableDeferred.insertColumn(column);
        select_list.rebuild();
        table.reload();
    });


    jQuery('#id_button_row_rm').click(function(event){
        var col_key = select_list.value();
        ResultsDataTableDeferred.removeColumn(ResultsDataTableDeferred.getColumn(col_key));
        select_list.with_table(ResultsDataTableDeferred).rebuild();
        });

    /* When user clicks on 'Save' button */
    $('#id_button_save').click(function() {
        data = table.view_as('html');
        $('textarea#text').val(data);
        $('form#post_to_analysis').submit();
        });


});
